package com.aiyige.page.advertisement.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;

import com.aiyige.MyApp;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.page.advertisement.model.AdResponse;
import com.aiyige.page.advertisement.util.AdUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.PreferenceUtil;
import com.aiyige.utils.RetrofitUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;


public class UpdateAdService extends IntentService {

    public UpdateAdService() {
        super("UpdateAdService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        PreferenceUtil.putLong(AdUtil.PREF_KEY_LAST_UPDATE_AD_TIMESTAMP, System.currentTimeMillis());
        AdUtil.clearUselessAd();
        try {
            Response<ResponseBody> response = ApiManager.getService().getAd("app_open").execute();
            if (response.code() != ResponseCode.OK) {
                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
            }
            String json = RetrofitUtil.getResponseBodyAsString(response);
            List<AdResponse> adResponseList = JSON.parseArray(json, AdResponse.class);
            AdUtil.parse(adResponseList);
            DownloadAdService.startService(MyApp.getAppContext());
        } catch (Exception e) {

        }
    }

    public static void startService(Context context) {
        context.startService(new Intent(context, UpdateAdService.class));
    }
}
